package com.jacken.mars.interceptor;

import com.jacken.mars.commons.annotation.BaseAnnotationNote;
import com.jacken.mars.commons.constant.CommonConstants;
import com.jacken.mars.commons.enums.ExceptionEnum;
import com.jacken.mars.entity.base.ApiRequestSupport;
import com.jacken.mars.utils.TokenUtils;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Objects;


/**
 * 采用拦截器的方式来做鉴权
 *
 * @author wq
 * @date 2020-12-29 20:41
 */
@Component
@AllArgsConstructor
public class AuthenticationInterceptor implements HandlerInterceptor {

    private final TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");

        if (handler instanceof HandlerMethod) {
            String token = request.getHeader(CommonConstants.TOKEN);
            if (StringUtils.isEmpty(token)) {
                token = request.getHeader(CommonConstants.TOKEN);
            }
            HandlerMethod hm = (HandlerMethod) handler;
            Method method = hm.getMethod();
            BaseAnnotationNote annotation = method.getAnnotation(BaseAnnotationNote.class);
            if (Objects.isNull(annotation)) {
                return true;
            }
            if (annotation.checkToken()) {
                if (StringUtils.isEmpty(token)) {
                    ApiRequestSupport.invokeExceptionWrapper(response, ExceptionEnum.TOKENRERROR);
                    return false;
                }
                //校验token
                if (tokenUtils.isTokenExpired(new Date())) {
                    ApiRequestSupport.invokeExceptionWrapper(response, ExceptionEnum.TOKENRERROR);
                    return false;
                } else {
                    Claims claim = tokenUtils.getTokenClaim(token);
                    if (Objects.nonNull(claim)) {
                        return true;
                    }
                }
                return false;
            }
        }
        return true;
    }
}
